
#include <cassert>
#include <windows.h>
#include "file.h"


using namespace fs;

struct File::Impl {
	HANDLE handle;

	Impl()
	{
		handle = INVALID_HANDLE_VALUE;
	}
};

File::File(): _pimpl( new Impl )
{
	
}

File::File(const std::string &filename, unsigned int openmode):_pimpl( new Impl )
{
	open( filename, openmode );
}

File::~File()
{
	::CloseHandle( _pimpl->handle );
	delete _pimpl;
}

bool File::open(const std::string &filename, unsigned int openmode)
{
	assert( _pimpl->handle == INVALID_HANDLE_VALUE );
	// @todo implement File::open()
	_pimpl->handle = CreateFileA( filename.c_str(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 );
	DWORD d = GetLastError();
	return isopen();
}

bool File::isopen()
{
	return _pimpl->handle != INVALID_HANDLE_VALUE;
}

size_t File::read(void *buf, size_t buflen)
{
	assert( _pimpl->handle != INVALID_HANDLE_VALUE );

	DWORD bytes_read = 0;
	ReadFile( _pimpl->handle, buf, buflen, &bytes_read, 0 );
	return bytes_read;
}

size_t File::size()
{
	assert( _pimpl->handle != INVALID_HANDLE_VALUE );

	return ::GetFileSize( _pimpl->handle, 0 );
}
